package com.sxfq.loansupermarket.backsystem.modular.arrival.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerAppointmentInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchCustomerAppointmentInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerAppointmentService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.DoctorInfo;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.TcInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.DepartmentInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author py
 * @Date 2019年4月19日23:15:54
 */
@Controller
@RequestMapping("/customerGuide")
public class CustomerGuideController extends BaseController {
    @Autowired
    ICustomerAppointmentService service;

    @Autowired
    private SqlMapper sqlMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    private String PREFIX = "/arrival/customer/";

    /**
     * 跳转到客户预约页面
     */
    @RequestMapping("")
    public String customerAppointmentQuery(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        if (redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"DoctorInfoList",0)== null) {
            String doctorListSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                    " where b.abbreviation='" + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"" + "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
            List<DoctorInfo> doctorInfoList = sqlMapper.selectList(doctorListSql, DoctorInfo.class);
            redisTemplate.opsForList().leftPush(ShiroKit.getUser().getAccount()+"DoctorInfoList",doctorInfoList);
        }
        model.addAttribute("doctorList", redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"DoctorInfoList",0));
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("sttleAccountsTime", redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"SttleAccountsTime",0));
        return PREFIX + "customer_guide_query.html";
    }

    /**
     * 到店 预约查询列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(SearchCustomerAppointmentInfo info) {
        if(info.getAbbreviation() == null || info.getAbbreviation() == "" || info.getAbbreviation() == "null"){
            return null;
        }else{
            Page<CustomerAppointmentInfo> page = new PageFactory<CustomerAppointmentInfo>().defaultPage();
            try {
                info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                List<CustomerAppointmentInfo> list = service.selectPageListByQueryGetGuideMap(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectPageListByQueryGetGuideMap(page, info);
                }
                page.setRecords(list);
                page.setTotal(service.getQueryPagesGuideCount(page, info));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.packForBT(page);
        }
    }

    /**
     * 统计查询
     */
    @RequestMapping(value = "/total", method = RequestMethod.GET)
    @ResponseBody
    public List<ConsultantInfo> changeTotal(String startTime, String endTime, String oneChannelValue, String doctor,
                                            String twoChannelValue, String thrChannelValue, String fieldTc, String treatmentUnit,
                                            String sreach) throws Exception {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        String tableName = tableHead + "customer_info";
        String contitionInfo = "";
        if (StringUtils.isNotBlank(startTime)) {
            contitionInfo += " and t.start_time >= '" + startTime + "' ";
        }
        if (StringUtils.isNotBlank(endTime)) {
            contitionInfo += " and t.start_time <= '" + endTime + "' ";
        }
        if (StringUtils.isNotBlank(fieldTc)) {
            contitionInfo += " and t.field_tc = '" + fieldTc + "' ";
        }
        if (StringUtils.isNotBlank(doctor)) {
            contitionInfo += " and t.doctor = '" + doctor + "' ";
        }
        if (StringUtils.isNotBlank(treatmentUnit)) {
            contitionInfo += " and t.treatment_unit = '" + treatmentUnit + "' ";
        }
        if (StringUtil.isNotEmpty(oneChannelValue)) {
            if (oneChannelValue.indexOf("请选择") == -1) {
                String oneChannel = "";
                String oneChannel2[] = oneChannelValue.split(",");
                if (oneChannel2.length == 1) {
                    oneChannel = oneChannel2[0];
                } else {
                    for (int i = 0; i < oneChannel2.length; i++) {
                        if (i == (oneChannel2.length - 1)) {
                            oneChannel += "'" + oneChannel2[i];
                        } else if (i == 0) {
                            oneChannel += oneChannel2[i] + "'" + ",";
                        } else {
                            oneChannel += "'" + oneChannel2[i] + "'" + ",";
                        }
                    }
                }
                contitionInfo += " and t.one_channel in ( '" + oneChannel + "') ";
            }
        }
        if (StringUtil.isNotEmpty(twoChannelValue)) {
            if (twoChannelValue.indexOf("请选择") == -1) {
                String twoChannel = "";
                String twoChannel2[] = twoChannelValue.split(",");
                if (twoChannel2.length == 1) {
                    twoChannel = twoChannel2[0];
                } else {
                    for (int i = 0; i < twoChannel2.length; i++) {
                        if (i == (twoChannel2.length - 1)) {
                            twoChannel += "'" + twoChannel2[i];
                        } else if (i == 0) {
                            twoChannel += twoChannel2[i] + "'" + ",";
                        } else {
                            twoChannel += "'" + twoChannel2[i] + "'" + ",";
                        }
                    }
                }
                contitionInfo += " and t.two_channel  in ('" + twoChannel + "') ";
            }
        }
        if (StringUtil.isNotEmpty(thrChannelValue)) {
            if (thrChannelValue.indexOf("请选择") == -1) {
                String thrChannel = "";
                String thrChannel2[] = thrChannelValue.split(",");
                if (thrChannel2.length == 1) {
                    thrChannel = thrChannel2[0];
                } else {
                    for (int i = 0; i < thrChannel2.length; i++) {
                        if (i == (thrChannel2.length - 1)) {
                            thrChannel += "'" + thrChannel2[i];
                        } else if (i == 0) {
                            thrChannel += thrChannel2[i] + "'" + ",";
                        } else {
                            thrChannel += "'" + thrChannel2[i] + "'" + ",";
                        }
                    }
                }
                contitionInfo += " and t.thr_channel in ('" + thrChannel + "') ";
            }
        }
        if (StringUtils.isNotBlank(sreach)) {
            contitionInfo += " and (t.customer_name like CONCAT('%','" + sreach + "','%') or t.customer_phone like CONCAT('%','" + sreach + "','%') or t.customer_phone2 like CONCAT('%','" + sreach + "','%') or" +
                    " t.wechat_number like CONCAT('%','" + sreach + "','%') or t.medical_record_number like CONCAT('%','" + sreach + "','%') or t.szm like CONCAT('%" + sreach + "%')) ";
        }       //总人数
        String sql = "select * from (select count(1) as countNum from " + tableName + " t  where 1=1 and t.isMarketTc=1 " + contitionInfo +
                //复诊预约人数
                " union all " +
                "select count(1) as countNum from " + tableName + " t  where 1=1 and (t.arrival_status=1 or t.arrival_status=6 or t.arrival_status=14) and t.isMarketTc=1 " + contitionInfo +
                //新诊预约人数
                " union all " +
                "select count(1) as countNum from " + tableName + " t  where 1=1 and (t.arrival_status=9 or t.arrival_status=10 or t.arrival_status=13) and t.isMarketTc=1 " + contitionInfo +
                " ) t" ;
        List<ConsultantInfo> infoList = sqlMapper.selectList(sql, ConsultantInfo.class);
        return infoList;
    }
}